if (!document.getElementById('jquery-js')) {
document.write('<script id="jquery-js" type="text/javascript" src="'+PTIncluder.imageServerURL+'house/js/jquery.js"></scr'+'ipt>');
}
if (!document.getElementById('fckeditor-js')) {
document.write('<script id="fckeditor-js" type="text/javascript" src="'+PTIncluder.imageServerURL+'plumtree/common/custom/RichTextEditors/FCKEditor_v264/fckeditor.js"></scr'+'ipt>');
}if (!document.getElementById('fckeditor-js-basic')) {
document.write('<script id="fckeditor-js-basic" type="text/javascript" src="'+PTIncluder.imageServerURL+'plumtree/common/custom/RichTextEditors/FCKeditor_basic.js"></scr'+'ipt>');
}



// Action ids
var aidClose = 0;
var aidUpdateState = 2;

var aidSave = 100;
var aidSaveAndClose = 102;
var aidPreview = 103;
var aidPublish = 104;
var aidCancelPreviewAndClose = 119;
var aidArchive = 122;
var aidRevert = 123;
var aidBrowse = 126;
var aidValidateLinks = 127;
var aidChangeContentItem = 128;
var aidUnlock = 129;
var aidCancelAndPreview = 130;
var aidCheckout = 131;
var aidCheckin = 132;
var aidCancelCheckout = 133;
var aidSubmit = 134;
var aidUncheckoutAndClose = 135;
var aidChangeOwner=136;
//SE-VV 54019: Commenting this out because this action id is not used anywhere else in the code.
//Also, this conflicts with the aidRemoveSearchIndex value, which is actually used in many other 
//places.
//var aidStartWorkflow = 137;
var aidRemoveSearchIndex = 137;
var aidExpire = 138;
var aidUnexpire = 139;
var aidRestoreVersion = 140;
var aidDeleteVersion = 141;
var aidChangeEventsVersion = 142;
var aidCheckinAndSubmit = 143;
var aidRemoveLink = 150;
var aidUpdateWorkflowData = 151;

var workflowSubmitAction = 0;
var workflowApproveAction = 1;
var workflowRejectAction = 2;
var workflowTransferAction = 3;

var doingAction = false; // required for IE
var closingWindow = false; // required for NN

// Submit an action
function SubmitAction(aid) {
	//Do nothing if already submitting an action
	if (doingAction) return;

	// Check for changes, set change flag
	hasChanged();

	
	//ADDED BY JDC!!!!!!!!!!!!!!!!!
	try{
		disp_alert("In submit action: action is "+aid);
		UpdateAndUnloadFCKEditors();
	}catch(err){alert("Error unloading FCKEditor: "+err);}
	
	doingAction = true;
	document.aform.aid.value = aid;
	if (msie) {
		document.aform.mTop.value = document.body.scrollTop;
	} else {
		document.aform.mTop.value = window.pageYOffset;
	}
	
	//submit the values for all RTCs on the page
	if(window.PTRichTextControl)
		window.PTRichTextControl.submitAll();
	
	//document.hps_ci_form.jsvars.value = session.toString();
	document.aform.submit();
}

//// Button actions

// Close the client
function CloseCIE() {
	if( amEditing  && hasChanged() && !doingAction ) {
		openAlertSave();
	} else {
		doEditorClose(itemId, false);
	}
}

// Update state
function UpdateState() {
		SubmitAction(aidUpdateState);
}

// Update Workflow Info
function UpdateWorkflowData() {
		SubmitAction(aidUpdateWorkflowData);
}

// Save
function SaveContentItem() {
	if ( validName(getItemName()) && hasChanged()) {
		SubmitAction(aidSave);
	}
}

//Checks item out
function Checkout() {
	SubmitAction(aidCheckout);
}

function Checkin(isSubmit) {
	if( amEditing && validName(getItemName()) && !doingAction ) {
		if (!isSubmit) {
			 openAlertCheckin();
		} else {
			 openAlertCheckinOnSubmit();
		}
	}
}

function CancelCheckout() {
	if (doingAction) return;

	if ( version == 1 ) { // never been checked in
		openAlertCancelCheckout();
	} else {
		if (confirm(_UI_STRING.ContentItemConfirmUndoCheckout)) {
	        SubmitAction(aidCancelCheckout);
		}
	}
}

// unlock this item
function Unlock() {
		SubmitAction(aidUnlock);
}

// Publish
function PublishItem() {
	if (doingAction) return;

	var itemName = getItemName();

	if (validName(itemName)) {
	    var confirmMessage = messageFormat(_UI_STRING.ContentItemConfirmPublish, itemName);
	    if ( hasChanged() || itemName == "") { //Make sure they know about save if changes or the're going to get "missing name" error
		    confirmMessage += '\n' + _UI_STRING.ContentItemConfirmOperationUnsaved;
	    }
	    if ( confirm(confirmMessage) ) {
		    SubmitAction(aidPublish);
	    }
	}
}
	
// Open the work item dialog for the associated work item
function OpenWorkItem(processId, workflowPortletBaseUri) {

	// The name of the dialog is wfWorkItem + [process id with '-' replaced by '_'
	open_dialog(PCSURL(workflowPortletBaseUri + '/workItem.do?p=' + 
	  processId), 'wfWorkItem' + processId.replace(/-/g, '_'), 580, 400 );
}

// Open the dialog to create a workflow instance containing this content item
function OpenCreateWorkflowInstanceDialog(contentItemId, ciEditorId, isEditing) {

  // If the user is editing the content item, they must first check it in
  if ((isEditing) && (hasChanged())) {
    if (confirm(_UI_STRING.ContentItemConfirmOperationUnsaved)) {
		  document.aform.waid.value = workflowSubmitAction;
			SaveContentItem(true);
	  }
	} else {
	  open_dialog('createWorkflowInstance.jsp?ciid=' + contentItemId + "&cieid=" + ciEditorId, 
	    'createWorkflowInstance' + contentItemId, 580, 420 );
	}
}

// Open the approve dialog for the associated work item
function DoWorkflowAction(processId, activityId, workflowPortletBaseUri, waid) {

  var page;
  if (waid == workflowApproveAction) {
		 page = 'approve.do';
	} else if (waid == workflowRejectAction) {
	   page = 'reject.do';
	} else if (waid == workflowTransferAction) {
	   page = 'transfer.do';
	} else {
	   // do nothing
		 return;
	}
	
	// The name of the dialog is approve + [process id with '-' replaced by '_'
	open_dialog(PCSURL(workflowPortletBaseUri + '/' + page + '?p=' + 
	  processId + '_' + activityId), 'approve' + processId.replace(/-/g, '_'), 580, 400 );
}

// Open the dialog to approve the associated work item
function OpenWFDialog(processId, activityId, workflowPortletBaseUri, isEditing, waid) {

  // If the user is editing the content item, they must first check it in
  if ((isEditing) && (hasChanged())) {
    if (confirm(_UI_STRING.ContentItemConfirmOperationUnsaved)) {
		  document.aform.waid.value = waid;
		  SaveContentItem(true);
	  }
	} else {
	    DoWorkflowAction(processId, activityId, workflowPortletBaseUri, waid);
	}
}

// Do preview
function doPreview(previewUrl) {
		var param = ((previewUrl.indexOf('?') == -1) ? '?' : '&') + "fbr=" + new Date().getTime(); // force browser refresh
		var previewWindow = null;
		/*if ( window.useEditThisPage ) {
				previewUrl = "etp_frameset.jsp?sid=" + sessionId + "&start=" + escape(previewUrl).replace(/\+/g,"%2b");
				previewWindow = open_new(previewUrl + param, "etp_preview_" + uwid());
		}
		else {
				previewWindow = window.open(previewUrl + param, "preview");
		}
		*/
		previewWindow = window.open(PCSURL(previewUrl + param), "preview");
		if ( previewWindow != null ) {
			previewWindow.focus();
		}
}

// Preview
function Preview() {
	SubmitAction(aidPreview);
}

// Expire
function ExpireItem() {
	if (doingAction) return;

	var itemName = getItemName();

	if (validName(itemName)) {
	    var confirmMessage = messageFormat(_UI_STRING.ContentItemConfirmExpire, itemName);
	    if ( hasChanged() || itemName == "") { //Make sure they know about save if changes or the're going to get "missing name" error
		    confirmMessage += '\n' + _UI_STRING.ContentItemConfirmOperationUnsaved;
	    }
	    if ( confirm(confirmMessage) ) {
		    SubmitAction(aidExpire);
	    }
	}
}

// Unexpire
function UnexpireItem() {
	if (doingAction) return;

	var itemName = getItemName();

	if (validName(itemName)) {
	    var confirmMessage = messageFormat(_UI_STRING.ContentItemConfirmUnexpire, itemName);
	    if ( hasChanged() || itemName == "") { //Make sure they know about save if changes or the're going to get "missing name" error
		    confirmMessage += '\n' + _UI_STRING.ContentItemConfirmOperationUnsaved;
	    }
	    if ( confirm(confirmMessage) ) {
		    SubmitAction(aidUnexpire);
	    }
	}
}


// New content item
function NewContentItem() {
	open_new_sm("ciEditor.jsp?sid=" + sessionId + "&bciid=" + itemId, "content_item_" + uwid(), false);
}

////Callbacks called by pop up after user presses Yes or No

// Save and close
function SaveAndClose() {
	if (validName(getItemName())) {
		SubmitAction(aidSaveAndClose);
	}
}

//Check in
function doCheckin(comment, keepCheckedOut) {
		document.aform.cargs.value = comment;
		document.aform.param0.value = keepCheckedOut;
		SubmitAction(aidCheckin);
}

function doCheckinAndSubmit(comment, keepCheckedOut) {
		document.aform.cargs.value = comment;
		document.aform.param0.value = keepCheckedOut;
		SubmitAction(aidCheckinAndSubmit);
}

//Remove link in Collab
function doRemoveLink(updateCollab) {
	document.aform.param0.value = updateCollab;
	SubmitAction(aidRemoveLink);
}

//Cancels checkout and deletes the item
function doCancelCheckoutDelete() {
	document.aform.param0.value = true;
	SubmitAction(aidCancelCheckout);
}

//Cancels checkout but does not delete item
function doCancelCheckoutLeave() {
	document.aform.param0.value = false;
	SubmitAction(aidCancelCheckout);
}

//Releases the checkout on the item, if there is one, without reverting
//it to its previous version like CancelCheckout does, and closes the window
function doUncheckoutAndClose() {
	if (amEditing) {
		SignalOpener({name:"EndEdit",id:itemId,endCheckout:true});
	}
	SubmitAction(aidUncheckoutAndClose);
}

function doSubmitterClose(didCheckout) {
	if (didCheckout) {
		doUncheckoutAndClose();
	} else {
		doEditorClose(itemId, false);
	}
}

//Advances item in workflow if possible, and just checks in otherwise
function doSimpleSubmit(canApprove) {
	if (validName(getItemName())) {
		if (amEditing) {
			SignalOpener({name:"EndEdit",id:itemId,endCheckout:true});
		}
	    SubmitAction(aidSubmit);
	}
}

//// Form validation

// Gets the current item name
function getItemName() {
	var itemName = initialItemName;
	if (defined(document.aform.itemname)) {
	    itemName = document.aform.itemname.value;
	}
	return itemName;
}

// Valid name is not empty
function validName(name) {
		if (name.match(/^\s*$/) ) {
				alert(_UI_STRING.ContentItemEmptyName);
//				nameField.select();
//				nameField.focus();
				return false;
		}
//		if (name.match(/[\\/:\*\?"<>|]/) ) {
//				alert(_UI_STRING.ContentItemInvalidName);
//		}
		return true;
}

// Valid target contains no non-alpha-numeric chars except spaces, underscores, or periods
function validTarget(nameField) {
		var name = nameField.value;
		if (name.match(/[^\w\s\.]/) ) {
				alert(_UI_STRING.ContentItemInvalidTarget);
				return false;
		}
		return true;
}

//// Routines to check and see if any fields have been changed

// Set changed
function setChanged() {
	document.aform.changed.value = "true";
}

//The value of a date picker has changed
function setWorkflowDueDatePickerChanged(pos) {
	setChanged();

	var dp = window["dp" + pos];
	var time = document.aform['ptime' + pos];
	if (dp.getDateString() != "" && time.selectedIndex == 0) {
	    time[time.length -1].selected = true;
	}
}

// user has changed something?
function hasChanged() {
alert("in orig has changed");
		var changed = document.aform.changed.value == "true";
		// If the changed flag is not set, then check the current form values for changes.
		// If it is set then there is no reason to check again
		if ( !changed ) {
				changed = FormElementChanged(document.aform);
				document.aform.changed.value = changed;
		}
		return changed;
}

// Loops through the form, finds items with the checkchanged property set to true.
// Form element's value is compared with its defaultValue.
// Works for input fields of type text, radio, and checkbox
function FormElementChanged(form) {
	var elements = form.elements;
	var element;
	var changed = false;
	var length = elements.length;

	for ( var i=0; i<length; ++i ) {
		element = elements[i];
		var checkchanged = false;
		//checkchanged = element.checkchanged; NETSCAPE HATES ON EXPANDO TAGS
		var name = element.name;
		checkchanged = (defined(name) &&
					    (name=="itemname" ||
						name == "pubSchedule" ||
					    name == "target" ||
						name.match(/^ptext\d+$/) ||
						name.match(/^pdate\d+$/)));

		if ( checkchanged && (
			    (element.type.toLowerCase() == "text" &&
				element.value != element.defaultValue) ||
				((element.type.toLowerCase() == "radio" ||
					element.type.toLowerCase() == "checkbox") &&
				element.checked != element.defaultChecked) ||
				(element.type.toLowerCase() == "textarea" &&
				((typeof(window["RTE" + name]) == "undefined") ? element.value != element.defaultValue : window["RTE" + name].isChanged) )
				) )
		{
			// A change has occured
			changed = true;
			break;
		}
	}
	return changed;
}

//// Open pop ups

// Open content item
function OpenCurrentItemVersion(ver) {
	var url = "ci_editor_jr.jsp?sid="+sessionId+"&ciid="+itemId+"&ver="+ver;
	open_new_sm(url, "content_item_" + sessionId + "_" + itemId + "_" + ver);
}

function openAlertSave() {
	var winName = 'ciEditorSave_' + clientId;
	openYesNoCancel(winName, "doEditorClose('" + itemId + "', true)", "doEditorClose('" + itemId + "', false);", "ContentItemSaveTitle", "ContentItemSaveQuestion");
}

function openAlertCancelCheckout() {
	var winName = 'ciEditorCancelCheck_' + clientId;
	openYesNoCancel(winName, "doCancelCheckoutDelete()", "doCancelCheckoutLeave()", "ContentItemCancelCheckoutTitle", "ContentItemCancelCheckoutQuestion");
}

function openAlertCheckin() {
	open_dialog('alertCheckin.jsp?cb=doCheckin','ciEditorCheckin_' + clientId, 580, 200); 
}

function openAlertCheckinOnSubmit() {
	open_dialog('alertCheckin.jsp?cb=doCheckinAndSubmit','ciEditorCheckin_' + clientId, 580, 200); 
}

function openAlertRemoveLink() {
	open_dialog('alertRemoveCollabLink.jsp?cb=doRemoveLink','ciEditorRemoveCollabLink_' + clientId, 380, 200); 
}

function openAlertApproveReject(title, type, callback, accountName, accountId, isUserAccount, stageName, alreadyPublished, canPublish, hasCollabLink) {

	// Determine if the publish option should be displayed.  Display if the can be published and has not
	// already been published or has changed
	var doPublish = false;
	if (canPublish && ((!alreadyPublished) || (hasChanged()))) {
		doPublish = true;
	}	

	if ( !validName(getItemName()) || doingAction ) {
	    return;
	}

	var accountParam = '&userid=';
	if(!isUserAccount) {
		accountParam = '&groupid=';
	}

	//If on workflow page, pass due date currently on page to popup
	//Otherwise just use the date that was set when the page initially loaded
	var dueParam;
	var wfDatePicker = window["dp" + workflowDueDatePos];
	
	if (typeof(wfDatePicker) != "undefined") {
		dueParam = '&pdate' + workflowDueDatePos + '=' + escape(wfDatePicker.getDateString());
		dueParam += '&ptime' + workflowDueDatePos + '=' + selectValue(document.aform['ptime' + workflowDueDatePos]);
	} else {
		dueParam = '&pdate' + workflowDueDatePos + '=' + escape(initialDueDate);
		dueParam += '&ptime' + workflowDueDatePos + '=' + initialDueTime;
	}
	var url = 'alertApproveReject.jsp?title=' + title + '&cb=' + callback + '&accountname=' + accountName + accountParam + accountId + '&stage=' + stageName + dueParam + '&pub=' + doPublish + '&collab=' + hasCollabLink + '&type=' + type;
	// note: need more height when the "update collab" option is displayed
	var winHeight = 290;
	if (hasCollabLink) {
		winHeight += 45;
	}
	if(type != 'complete') {
	    winHeight += 40;
	}

	if(doPublish) {
		winHeight += 75; //warning plus publish option
	}

	open_dialog(url, 'ciEditorApproveReject_' + clientId, 500, winHeight);
}


//Version control functions

//Restore checked version
function Restore() {
	var priCB;
	for (var i=0; i < numVersions; i++) {
	    var cb = eval("document.aform.versionCB" + i);
		if (cb.checked) {
		    if (!priCB) {
			    priCB = cb;
			} else {
				alert(_UI_STRING.VersionControlRestoreTwoChecked);
				return;
			}
		}
	}

	if (!priCB) {
		alert(_UI_STRING.VersionControlRestoreNoneChecked);
	} else {
		if (priCB.value == activeVersionNumber) {
			alert(_UI_STRING.VersionControlRestoreActiveChecked);
		} else {
			if ( confirm(messageFormat(_UI_STRING.VersionPromptMakeActive, priCB.value) ) ) {
				document.aform.param0.value = priCB.value;
				SubmitAction(aidRestoreVersion);
			}
		}
	}
}

//Compare checked versions
function Compare() {
	var priCB;
	var secCB;
	for (var i=0; i < numVersions; i++) {
	    var cb = eval("document.aform.versionCB" + i);
		if (cb.checked) {
		    if (!priCB) {
			    priCB = cb;
			} else if (!secCB) {
			    secCB = cb;
			} else {
				alert(_UI_STRING.VersionControlCompareThreeChecked);
				return;
			}
		}
	}

	if (!priCB || !secCB) {
	    alert(_UI_STRING.VersionControlCompareNeedTwo);
	} else {
	    open_new_sm("compare_versions.jsp?sid="+sessionId+"&ciid="+itemId+"&ver1="+priCB.value+"&ver2="+secCB.value, "comparevers_"+sessionId+"_"+priCB.value+"_"+secCB.value, true);
	}
}

//User has clicked icon to show version's events
function showVersionEvents(versionNum) {
	document.aform.param0.value = versionNum;
	SubmitAction(aidChangeEventsVersion);
}

//// Functions dealing with windows loading and unloading and communicating with each other

// Signal handler for signals from clients
function SignalHandler(signal) {
		if (signal.name == "ReloadPage") {
				SignalOpener(signal);
				UpdateState();
				return true;
		}
		if (signal.name == "NewItemCreated") {
				SignalOpener({name:"ReloadPage"});
				UpdateState();
				return true;
		}
		if (signal.name == "UpdateState") {
				UpdateState();
				return true;
		}
		if (signal.name == "UpdateWorkflowData") {
				UpdateWorkflowData();
				return true;
		}
		return SignalOpener(signal);
}

function ReloadPortlets() {

		// refresh My Activities table control
		if (window.opener &&
		    (typeof(window.opener.closed) != "unknown") &&
		    !window.opener.closed)
		{
			//CIE opened from my activites
			if( defined(window.opener.PTWF_MyActivitiesControl) )
			{
				window.opener.PTWF_MyActivitiesControl.reload();
			}
			//CIE opened from Explorer opened from page w/ My Activites
			else if( window.opener.opener &&
				 (typeof(window.opener.opener.closed) != "unknown") &&
				 !window.opener.opener.closed &&
				 defined(window.opener.opener.PTWF_MyActivitiesControl) )
			{
				window.opener.opener.PTWF_MyActivitiesControl.reload();
			}
		}



		// refresh Workflow Tracker table control
		if (window.opener &&
		    (typeof(window.opener.closed) != "unknown") &&
		    !window.opener.closed)
		{
			//CIE opened from my activites
			if( defined(window.opener.PTCS_WorkflowTrackerControl) )
			{
				window.opener.PTCS_WorkflowTrackerControl.reload();
			}
			//CIE opened from Explorer opened from page w/ My Activites
			else if( window.opener.opener &&
				 (typeof(window.opener.opener.closed) != "unknown") &&
				 !window.opener.opener.closed &&
				 defined(window.opener.opener.PTCS_WorkflowTrackerControl) )
			{
				window.opener.opener.PTCS_WorkflowTrackerControl.reload();
			}
		}
}


// Reload navigator page
function ReloadNavigator(isNew, itemId) {
		if (isNew) {
				SignalOpener({name:"NewItemCreated", itemId:itemId});
		}
		else {
				SignalOpener({name:"ReloadPage"});
		}
}

// On load
function OnLoad()
{

	// Set the initial focus item
	//EditorStartupFocus(document.hps_ci_form.itemname);

	// Set the scroll position after setting the focus
	var scrollCmd;
	if (msie) {
		scrollCmd = 'document.body.scrollTop = mTop;'
	} else {
	    scrollCmd = 'window.scrollTo(0, mTop);'
	}
	setTimeout(scrollCmd, 1);

	if ( amEditing ) {
		SignalOpener({name:"StartEdit",id:itemId});
	}

	// Deal with alert message
    if (alertMessage != '') {
		alert(alertMessage);
    }

}


//***************MODIFIED BY JDC
// user has changed something?
function hasChanged() {
		var changed = document.aform.changed.value == "true";
		// If the changed flag is not set, then check the current form values for changes.
		// If it is set then there is no reason to check again
		if ( !changed ) {
				changed = FormElementChanged(document.aform);
				try{if (!changed)
					changed = CheckFCKChanged();}catch(err){}
				document.aform.changed.value = changed;
		}
		return changed;
}


